package com.team6.stickynote.sql;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.team6.stickynote.beans.StickyNoteBean;

import java.util.ArrayList;
import java.util.List;

public class DBAdapter {
    private static final String DB_NAME = "sticky.db";
    private static final String DB_TABLE = "data";
    private static final int DB_VERSION = 1;

    public static final String KEY_ID = "_id";
    public static final String KEY_Title = "_title";
    public static final String KEY_Text = "_text";

    private SQLiteDatabase db;//实例
    private final Context context;
    private DBOpenHelper dbOpenHelper;

    public DBAdapter(Context _context) {
        context = _context;
    }

    /**
     * Close the database
     */
    public void close() {
        if (db != null) {
            db.close();
            db = null;
        }
    }

    /**
     * Open the database
     */
    public void open() throws SQLiteException {
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        try {
            db = dbOpenHelper.getWritableDatabase();
            Log.d("AAAA", "vector");
        } catch (SQLiteException ex) {
            db = dbOpenHelper.getReadableDatabase();
        }
    }

    //添加数据
    public long insert(StickyNoteBean stickyNoteBean) {
        ContentValues newValues = new ContentValues();

        //newValues.put(KEY_ID, stickyNoteBean.getId());
        newValues.put(KEY_Title, stickyNoteBean.getTitle());
        newValues.put(KEY_Text, stickyNoteBean.getText());

        return db.insert(DB_TABLE, null, newValues);
    }

    /**
     * 查询全部数据
     *
     * @return 数据集合
     */
    @Nullable
    public ArrayList<StickyNoteBean> queryAllData() {
        Cursor results = db.query(DB_TABLE, new String[]{KEY_ID, KEY_Title, KEY_Text},
                null, null, null, null, null);
        return ConvertToNoteBean(results);
    }

    /**
     * @param id 目标 ID
     * @return 结果
     */
    @Nullable
    public StickyNoteBean queryOneData(long id) {
        Cursor results = db.query(DB_TABLE, new String[]{KEY_ID, KEY_Title, KEY_Text},
                KEY_ID + "=" + id, null, null, null, null);
        ArrayList<StickyNoteBean> stickyNoteBeans = ConvertToNoteBean(results);
        if (stickyNoteBeans.size() > 0) {
            return stickyNoteBeans.get(0);
        } else {
            return null;
        }
    }

    @SuppressLint("Range")
    @NonNull
    private ArrayList<StickyNoteBean> ConvertToNoteBean(Cursor cursor) {
        int resultCounts = cursor.getCount();
        ArrayList<StickyNoteBean> stickyNoteBeans = new ArrayList<>();
        if (resultCounts == 0 || !cursor.moveToFirst()) {
            return stickyNoteBeans;
        }

        for (int i = 0; i < resultCounts; i++) {
            StickyNoteBean stickyNoteBean = new StickyNoteBean();
            stickyNoteBean.setId(cursor.getLong(0));
            stickyNoteBean.setTitle(cursor.getString(cursor.getColumnIndex(KEY_Title)));
            stickyNoteBean.setText(cursor.getString(cursor.getColumnIndex(KEY_Text)));
            stickyNoteBeans.add(stickyNoteBean);
            cursor.moveToNext();
        }
        return stickyNoteBeans;
    }

    //删除全部和一条
    public long deleteAllData() {
        return db.delete(DB_TABLE, null, null);
    }

    public long deleteOneData(long id) {
        return db.delete(DB_TABLE, KEY_ID + "=" + id, null);
    }

    //更新一条数据
    public long updateOneData(long id, StickyNoteBean stickyNoteBean) {
        ContentValues updateValues = new ContentValues();

        updateValues.put(KEY_ID, stickyNoteBean.getId());
        updateValues.put(KEY_Title, stickyNoteBean.getTitle());
        updateValues.put(KEY_Text, stickyNoteBean.getText());

        return db.update(DB_TABLE, updateValues, KEY_ID + "=" + id, null);
    }

    public int updateData(StickyNoteBean note) {

        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("title", note.getTitle());
        values.put("text", note.getText());

        return db.update(DB_TABLE, values, "id like ?", new String[]{String.valueOf(note.getId())});
    }

    private SQLiteDatabase getWritableDatabase() {
        throw new RuntimeException("Stub!");
    }

    /**
     * 静态Helper类，用于建立、更新和打开数据库
     */
    private static class DBOpenHelper extends SQLiteOpenHelper {

        public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        private static final String DB_CREATE = "create table " +
                DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " +
                KEY_Title + " text , " + KEY_Text + " text);";

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
            _db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
            onCreate(_db);
        }
    }

    //无用代码
//    public List<Note> queryAllFromDb() {
//
//        SQLiteDatabase db = getWritableDatabase();
//        List<Note> noteList = new ArrayList<>();
//
//        Cursor cursor = db.query(TABLE_NAME_NOTE, null, null, null, null, null, null);
//        if (cursor != null) {
//            while (cursor.moveToNext()) {
//                String id = cursor.getString(cursor.getColumnIndex("id"));
//                String title = cursor.getString(cursor.getColumnIndex("title"));
//                String content = cursor.getString(cursor.getColumnIndex("content"));
//                String createTime = cursor.getString(cursor.getColumnIndex("create_time"));
//
//                Note note = new Note();
//                note.setId(id);
//                note.setTitle(title);
//                note.setContent(content);
//                note.setCreatedTime(createTime);
//
//                noteList.add(note);
//            }
//            cursor.close();
//        }
//
//        return noteList;

}
